package logger

import (
	"log"
	"os"

	go_logger "github.com/phachon/go-logger"
)

const LOGGER_FILE_PATH = "logs/"

var Logger *go_logger.Logger

func LoadLogger() {
	Logger = go_logger.NewLogger()
	fileConfig := &go_logger.FileConfig{
		Filename: LOGGER_FILE_PATH + "zlm.log",
		LevelFileName: map[int]string{
			Logger.LoggerLevel("error"): LOGGER_FILE_PATH + "zlm.error.log",
			Logger.LoggerLevel("info"):  LOGGER_FILE_PATH + "zlm.info.log",
			Logger.LoggerLevel("debug"): LOGGER_FILE_PATH + "zlm.debug.log",
		},
		MaxSize:    32 * 1024 * 1024,
		MaxLine:    100000,
		DateSlice:  "h",
		JsonFormat: false,
		Format:     "%millisecond_format% [%level_string%] [%file%:%line%] %body%",
	}
	Logger.Attach("file", go_logger.LOGGER_LEVEL_DEBUG, fileConfig)
	Logger.SetAsync()
}

func ExitLogger() {
	Logger.Flush()
	Logger = nil
}

func NewLogger(modName string, level string, filePath string) *go_logger.Logger {
	l := go_logger.NewLogger()
	if l == nil {
		log.Println("new logger failed")
		return nil
	}

	if err := l.Detach("console"); err != nil {
		log.Println(err)
	}

	consoleCfg := &go_logger.ConsoleConfig{
		Color:      true,
		JsonFormat: false,
		Format:     "%millisecond_format% [%level_string%] [%file%:%line%] %body%",
	}

	l.Attach("console", go_logger.LOGGER_LEVEL_DEBUG, consoleCfg)

	if filePath != "" {
		fileConfig := &go_logger.FileConfig{
			Filename: filePath + "/" + modName + ".log",
			LevelFileName: map[int]string{
				Logger.LoggerLevel("error"): filePath + "/" + modName + "_error.log",
				Logger.LoggerLevel("info"):  filePath + "/" + modName + "_info.log",
				Logger.LoggerLevel("debug"): filePath + "/" + modName + "_debug.log",
			},
			MaxSize:    10 * 1024 * 1024,
			MaxLine:    1000,
			DateSlice:  "h",
			JsonFormat: false,
			Format:     "%millisecond_format% [%level_string%] [%file%:%line%] %body%",
		}
		l.Attach("file", go_logger.LOGGER_LEVEL_DEBUG, fileConfig)
	}

	l.SetAsync()

	return l
}

func GetLogger(prefix string) (*log.Logger, *log.Logger) {
	logErr := log.New(os.Stderr, "["+prefix+"-error]", log.Ldate|log.Lmicroseconds|log.Lshortfile)
	logInfo := log.New(os.Stdout, "["+prefix+"-info]", log.Ldate|log.Lmicroseconds|log.Lshortfile)
	return logErr, logInfo
}
